13 use Liuggio\StatsdClient\Factory\StatsdDataFactory
;
15 use MediaHandlerFactory
;
16 use MediaWiki\Linker\LinkRenderer
;
17 use MediaWiki\Linker\LinkRendererFactory
;
18 use MediaWiki\Services\SalvageableService
;
19 use MediaWiki\Services\ServiceContainer
;
20 use MediaWiki\Services\NoSuchServiceException
;
26 use SearchEngineConfig
;
27 use SearchEngineFactory
;
31 use WatchedItemQueryService
;
35 use VirtualRESTServiceClient
;
36 use MediaWiki\Interwiki\InterwikiLookup
;
39 * Service locator for MediaWiki core services.
41 * This program is free software; you can redistribute it and/or modify
42 * it under the terms of the GNU General Public License as published by
43 * the Free Software Foundation; either version 2 of the License, or
44 * (at your option) any later version.
46 * This program is distributed in the hope that it will be useful,
47 * but WITHOUT ANY WARRANTY; without even the implied warranty of
48 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
49 * GNU General Public License for more details.
51 * You should have received a copy of the GNU General Public License along
52 * with this program; if not, write to the Free Software Foundation, Inc.,
53 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
54 * http://www.gnu.org/copyleft/gpl.html
62 * MediaWikiServices is the service locator for the application scope of MediaWiki.
63 * Its implemented as a simple configurable DI container.
64 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
65 * the network of service objects that defines MediaWiki's application logic.
66 * It acts as an entry point to MediaWiki's dependency injection mechanism.
68 * Services are defined in the "wiring" array passed to the constructor,
69 * or by calling defineService().
71 * @see docs/injection.txt for an overview of using dependency injection in the
72 * MediaWiki code base.
74 class MediaWikiServices
extends ServiceContainer
{
77 * @var MediaWikiServices|null
79 private static $instance = null;
82 * Returns the global default instance of the top level service locator.
86 * The default instance is initialized using the service instantiator functions
87 * defined in ServiceWiring.php.
89 * @note This should only be called by static functions! The instance returned here
90 * should not be passed around! Objects that need access to a service should have
91 * that service injected into the constructor, never a service locator!
93 * @return MediaWikiServices
95 public static function getInstance() {
96 if ( self
::$instance === null ) {
97 // NOTE: constructing GlobalVarConfig here is not particularly pretty,
98 // but some information from the global scope has to be injected here,
99 // even if it's just a file name or database credentials to load
100 // configuration from.
101 $bootstrapConfig = new GlobalVarConfig();
102 self
::$instance = self
::newInstance( $bootstrapConfig, 'load' );
105 return self
::$instance;
109 * Replaces the global MediaWikiServices instance.
113 * @note This is for use in PHPUnit tests only!
115 * @throws MWException if called outside of PHPUnit tests.
117 * @param MediaWikiServices $services The new MediaWikiServices object.
119 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
121 public static function forceGlobalInstance( MediaWikiServices
$services ) {
122 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
123 throw new MWException( __METHOD__
. ' must not be used outside unit tests.' );
126 $old = self
::getInstance();
127 self
::$instance = $services;
133 * Creates a new instance of MediaWikiServices and sets it as the global default
134 * instance. getInstance() will return a different MediaWikiServices object
135 * after every call to resetGlobalInstance().
139 * @warning This should not be used during normal operation. It is intended for use
140 * when the configuration has changed significantly since bootstrap time, e.g.
141 * during the installation process or during testing.
143 * @warning Calling resetGlobalInstance() may leave the application in an inconsistent
144 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
145 * any of the services managed by MediaWikiServices exist. If any service objects
146 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
147 * with the operation of the services managed by the new MediaWikiServices.
148 * Operating with a mix of services created by the old and the new
149 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
150 * Any class implementing LAZY LOADING is especially prone to this problem,
151 * since instances would typically retain a reference to a storage layer service.
153 * @see forceGlobalInstance()
154 * @see resetGlobalInstance()
155 * @see resetBetweenTest()
157 * @param Config|null $bootstrapConfig The Config object to be registered as the
158 * 'BootstrapConfig' service. This has to contain at least the information
159 * needed to set up the 'ConfigFactory' service. If not given, the bootstrap
160 * config of the old instance of MediaWikiServices will be re-used. If there
161 * was no previous instance, a new GlobalVarConfig object will be used to
162 * bootstrap the services.
164 * @param string $quick Set this to "quick" to allow expensive resources to be re-used.
165 * See SalvageableService for details.
167 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
168 * Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
171 public static function resetGlobalInstance( Config
$bootstrapConfig = null, $quick = '' ) {
172 if ( self
::$instance === null ) {
173 // no global instance yet, nothing to reset
177 self
::failIfResetNotAllowed( __METHOD__
);
179 if ( $bootstrapConfig === null ) {
180 $bootstrapConfig = self
::$instance->getBootstrapConfig();
183 $oldInstance = self
::$instance;
185 self
::$instance = self
::newInstance( $bootstrapConfig );
186 self
::$instance->importWiring( $oldInstance, [ 'BootstrapConfig' ] );
188 if ( $quick === 'quick' ) {
189 self
::$instance->salvage( $oldInstance );
191 $oldInstance->destroy();
197 * Salvages the state of any salvageable service instances in $other.
199 * @note $other will have been destroyed when salvage() returns.
201 * @param MediaWikiServices $other
203 private function salvage( self
$other ) {
204 foreach ( $this->getServiceNames() as $name ) {
205 // The service could be new in the new instance and not registered in the
206 // other instance (e.g. an extension that was loaded after the instantiation of
207 // the other instance. Skip this service in this case. See T143974
209 $oldService = $other->peekService( $name );
210 } catch ( NoSuchServiceException
$e ) {
214 if ( $oldService instanceof SalvageableService
) {
215 /** @var SalvageableService $newService */
216 $newService = $this->getService( $name );
217 $newService->salvage( $oldService );
225 * Creates a new MediaWikiServices instance and initializes it according to the
226 * given $bootstrapConfig. In particular, all wiring files defined in the
227 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
229 * @param Config|null $bootstrapConfig The Config object to be registered as the
230 * 'BootstrapConfig' service.
232 * @param string $loadWiring set this to 'load' to load the wiring files specified
233 * in the 'ServiceWiringFiles' setting in $bootstrapConfig.
235 * @return MediaWikiServices
236 * @throws MWException
237 * @throws \FatalError
239 private static function newInstance( Config
$bootstrapConfig, $loadWiring = '' ) {
240 $instance = new self( $bootstrapConfig );
242 // Load the default wiring from the specified files.
243 if ( $loadWiring === 'load' ) {
244 $wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
245 $instance->loadWiringFiles( $wiringFiles );
248 // Provide a traditional hook point to allow extensions to configure services.
249 Hooks
::run( 'MediaWikiServices', [ $instance ] );
255 * Disables all storage layer services. After calling this, any attempt to access the
256 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
261 * @warning This is intended for extreme situations only and should never be used
262 * while serving normal web requests. Legitimate use cases for this method include
263 * the installation process. Test fixtures may also use this, if the fixture relies
266 * @see resetGlobalInstance()
267 * @see resetChildProcessServices()
269 public static function disableStorageBackend() {
270 // TODO: also disable some Caches, JobQueues, etc
271 $destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
272 $services = self
::getInstance();
274 foreach ( $destroy as $name ) {
275 $services->disableService( $name );
278 ObjectCache
::clear();
282 * Resets any services that may have become stale after a child process
283 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
284 * to call this method from the parent process.
288 * @note This is intended for use in the context of process forking only!
290 * @see resetGlobalInstance()
291 * @see disableStorageBackend()
293 public static function resetChildProcessServices() {
294 // NOTE: for now, just reset everything. Since we don't know the interdependencies
295 // between services, we can't do this more selectively at this time.
296 self
::resetGlobalInstance();
298 // Child, reseed because there is no bug in PHP:
299 // http://bugs.php.net/bug.php?id=42465
300 mt_srand( getmypid() );
304 * Resets the given service for testing purposes.
308 * @warning This is generally unsafe! Other services may still retain references
309 * to the stale service instance, leading to failures and inconsistencies. Subclasses
310 * may use this method to reset specific services under specific instances, but
311 * it should not be exposed to application logic.
313 * @note With proper dependency injection used throughout the codebase, this method
314 * should not be needed. It is provided to allow tests that pollute global service
315 * instances to clean up.
317 * @param string $name
318 * @param bool $destroy Whether the service instance should be destroyed if it exists.
319 * When set to false, any existing service instance will effectively be detached
320 * from the container.
322 * @throws MWException if called outside of PHPUnit tests.
324 public function resetServiceForTesting( $name, $destroy = true ) {
325 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
326 throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
329 $this->resetService( $name, $destroy );
333 * Convenience method that throws an exception unless it is called during a phase in which
334 * resetting of global services is allowed. In general, services should not be reset
335 * individually, since that may introduce inconsistencies.
339 * This method will throw an exception if:
341 * - self::$resetInProgress is false (to allow all services to be reset together
342 * via resetGlobalInstance)
343 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
344 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
346 * This method is intended to be used to safeguard against accidentally resetting
347 * global service instances that are not yet managed by MediaWikiServices. It is
348 * defined here in the MediaWikiServices services class to have a central place
349 * for managing service bootstrapping and resetting.
351 * @param string $method the name of the caller method, as given by __METHOD__.
353 * @throws MWException if called outside bootstrap mode.
355 * @see resetGlobalInstance()
356 * @see forceGlobalInstance()
357 * @see disableStorageBackend()
359 public static function failIfResetNotAllowed( $method ) {
360 if ( !defined( 'MW_PHPUNIT_TEST' )
361 && !defined( 'MW_PARSER_TEST' )
362 && !defined( 'MEDIAWIKI_INSTALL' )
363 && !defined( 'RUN_MAINTENANCE_IF_MAIN' )
364 && defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
366 throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
371 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
372 * This has to contain at least the information needed to set up the 'ConfigFactory'
375 public function __construct( Config
$config ) {
376 parent
::__construct();
378 // Register the given Config object as the bootstrap config service.
379 $this->defineService( 'BootstrapConfig', function() use ( $config ) {
384 // CONVENIENCE GETTERS ////////////////////////////////////////////////////
387 * Returns the Config object containing the bootstrap configuration.
388 * Bootstrap configuration would typically include database credentials
389 * and other information that may be needed before the ConfigFactory
390 * service can be instantiated.
392 * @note This should only be used during bootstrapping, in particular
393 * when creating the MainConfig service. Application logic should
394 * use getMainConfig() to get a Config instances.
399 public function getBootstrapConfig() {
400 return $this->getService( 'BootstrapConfig' );
405 * @return ConfigFactory
407 public function getConfigFactory() {
408 return $this->getService( 'ConfigFactory' );
412 * Returns the Config object that provides configuration for MediaWiki core.
413 * This may or may not be the same object that is returned by getBootstrapConfig().
418 public function getMainConfig() {
419 return $this->getService( 'MainConfig' );
426 public function getSiteLookup() {
427 return $this->getService( 'SiteLookup' );
434 public function getSiteStore() {
435 return $this->getService( 'SiteStore' );
440 * @return InterwikiLookup
442 public function getInterwikiLookup() {
443 return $this->getService( 'InterwikiLookup' );
448 * @return StatsdDataFactory
450 public function getStatsdDataFactory() {
451 return $this->getService( 'StatsdDataFactory' );
456 * @return EventRelayerGroup
458 public function getEventRelayerGroup() {
459 return $this->getService( 'EventRelayerGroup' );
464 * @return SearchEngine
466 public function newSearchEngine() {
467 // New engine object every time, since they keep state
468 return $this->getService( 'SearchEngineFactory' )->create();
473 * @return SearchEngineFactory
475 public function getSearchEngineFactory() {
476 return $this->getService( 'SearchEngineFactory' );
481 * @return SearchEngineConfig
483 public function getSearchEngineConfig() {
484 return $this->getService( 'SearchEngineConfig' );
489 * @return SkinFactory
491 public function getSkinFactory() {
492 return $this->getService( 'SkinFactory' );
499 public function getDBLoadBalancerFactory() {
500 return $this->getService( 'DBLoadBalancerFactory' );
505 * @return LoadBalancer The main DB load balancer for the local wiki.
507 public function getDBLoadBalancer() {
508 return $this->getService( 'DBLoadBalancer' );
513 * @return WatchedItemStore
515 public function getWatchedItemStore() {
516 return $this->getService( 'WatchedItemStore' );
521 * @return WatchedItemQueryService
523 public function getWatchedItemQueryService() {
524 return $this->getService( 'WatchedItemQueryService' );
531 public function getCryptRand() {
532 return $this->getService( 'CryptRand' );
537 * @return MediaHandlerFactory
539 public function getMediaHandlerFactory() {
540 return $this->getService( 'MediaHandlerFactory' );
545 * @return MimeAnalyzer
547 public function getMimeAnalyzer() {
548 return $this->getService( 'MimeAnalyzer' );
553 * @return ProxyLookup
555 public function getProxyLookup() {
556 return $this->getService( 'ProxyLookup' );
561 * @return GenderCache
563 public function getGenderCache() {
564 return $this->getService( 'GenderCache' );
571 public function getLinkCache() {
572 return $this->getService( 'LinkCache' );
577 * @return LinkRendererFactory
579 public function getLinkRendererFactory() {
580 return $this->getService( 'LinkRendererFactory' );
584 * LinkRenderer instance that can be used
585 * if no custom options are needed
588 * @return LinkRenderer
590 public function getLinkRenderer() {
591 return $this->getService( 'LinkRenderer' );
596 * @return TitleFormatter
598 public function getTitleFormatter() {
599 return $this->getService( 'TitleFormatter' );
604 * @return TitleParser
606 public function getTitleParser() {
607 return $this->getService( 'TitleParser' );
614 public function getMainObjectStash() {
615 return $this->getService( 'MainObjectStash' );
620 * @return \WANObjectCache
622 public function getMainWANObjectCache() {
623 return $this->getService( 'MainWANObjectCache' );
630 public function getLocalServerObjectCache() {
631 return $this->getService( 'LocalServerObjectCache' );
636 * @return VirtualRESTServiceClient
638 public function getVirtualRESTServiceClient() {
639 return $this->getService( 'VirtualRESTServiceClient' );
642 ///////////////////////////////////////////////////////////////////////////
643 // NOTE: When adding a service getter here, don't forget to add a test
644 // case for it in MediaWikiServicesTest::provideGetters() and in
645 // MediaWikiServicesTest::provideGetService()!
646 ///////////////////////////////////////////////////////////////////////////